// pages/mine/mine.js
var app =getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    points:'',
    id:'',//课程码为courseId，签到码为courseId
    role:'',//课程码role为‘course’，签到码为签到者（出示二维码）userId
    records:'',
    user:'',//出示二维码的人的user
    status:'0',//0未签到，1签到，2迟到
    endTime:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    //console.log("onLoad");
    // let that = this;
    // that.setData({
    //   status: options.status//取得签到状态
    // })
    //查userInfo
    wx.request({
      url: app.globalData.url + 'v1/user/'+app.globalData.userInfo.id,
      method: 'get',
      data: {
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        // console.log("onLoad:"+res);
        that.setData({
          points: res.data.user.points
        })
      }
    })
  },
  //修改签到状态status
  update_status:function(res){
    app.globalData.records.status = 1
    console.log(app.globalData.records)
    wx.request({
      method: "post",
      url: app.globalData.url + 'v1/records/update', 
      header: {
        'content-type': 'application/json' // 默认值
      },
      data: app.globalData.records,
      success (res) {
        console.log(res)
      }
    })
  },
  //时间比较
  timeminus:function(end_time){
    var date = new Date();
    var s1 = date.getTime();
    var s2 = end_time.getTime();
    return s2-s1;
  },

  getScancode:function(){
    console.log(25);
    var _this=this;
    // 允许从相机和相册扫码
    wx.scanCode({
      success: (res) => {
        var result = res.result;
        // var scanType = res.scanType;
        // var charSet = res.charSet;
        // var path = res.path;
        var scanInfo=result.split(",");
       
        _this.setData({
          id:scanInfo[1],//课程码为courseId，签到码为courseId
          role:scanInfo[0]//课程码role为‘course’，签到码为具体userId
        })
        console.log("id:"+_this.data.id);
        console.log("role:"+_this.data.role);
        console.log(res);
        if(_this.data.role=="course"){
          console.log("go to course");
          wx.request({
              url:app.globalData.url+'v1/records/'+app.globalData.userInfo.id+'/'+_this.data.id, 
              data:{  
              },
              header:{  
                'content-type':'application/json'
              }, 
              // dataType:'JSON',  
              // responseType:'text', 
              success:function(res){
                  console.log(res);
                  console.log(app.globalData.userInfo.id);
                  console.log(_this.data.id);
                  if(res.data.result=="fail"){//没查到，则插入               
                    wx.request({
                        url:app.globalData.url+'v1/records/',
                        method:"POST",
                        data:{
                          id:"",
                          userId:app.globalData.userInfo.id,
                          courseId:_this.data.id,
                          type:"0",
                          status:"0",
                          scores:"",
                          comments:""
                        },
                        header:{  
                           'content-type':'application/json'
                        },
                        type:'POST',  
                        // dataType:'JSON',  
                        // responseType:'text', 
                        success:function(res){
                            console.log(res);
  
                        },
                    })
                    wx.showToast({
                      title: '加入课堂成功！',
                      icon: 'success',
                      duration: 1500
                    })

                  }else{
                    wx.showToast({
                      title: '不能重复加入课堂！',
                      icon: 'error',
                      duration: 1500
                    })
                    console.log("加入失败！");
                  }

          
              },
          })
        }else{//签到码
          console.log("go to else");
          var type;
          //判断是否是签到员
          console.log("courseID:"+_this.data.id);
          console.log("userID:"+app.globalData.userInfo.id);
          wx.request({//按userid，courseid查找签到员的records
            url:app.globalData.url+'v1/records/'+app.globalData.userInfo.id+'/'+_this.data.id, 
            data:{  
            },
            header:{  
              'content-type':'application/json'
            }, 
            // dataType:'JSON',  
            // responseType:'text', 
            success:function(res){
                console.log(res);
                // _this.setData({
                //   recordsId:res.data.records.id
                // })
                // var records=res;
                // console.log("records:"+records);
                if(res.data.records.type==1){//是签到员
                  //判断课程是否开启签到
                  wx.request({//按courseid查course表
                    url:app.globalData.url+'v1/courses/id/'+_this.data.id, 
                    data:{  
                    },
                    header:{  
                       'content-type':'application/json'
                    },
                    method:'GET',  
                    // dataType:'JSON',  
                    // responseType:'text', 
                    success:function(res){
                        console.log(res);
                        if(res.data.courses.state==1){//课可以签到
                          //判断签到状态
                          let date = new Date(res.data.courses.endTime)
                          _this.setData({
                            endTime : date})
                          if(_this.timeminus(_this.data.endTime)>=0){//正常签到
                            _this.setData({
                              status : "1"})
                          }else{//迟到
                            _this.setData({
                              status : "2"})

                          }

                          //按userid，courseid查找出示二维码的人的records
                          wx.request({
                            url:app.globalData.url+'v1/records/'+_this.data.role+'/'+_this.data.id, 
                            data:{  
                            },
                            header:{  
                              'content-type':'application/json'
                            }, 
                            success:function(res){
                                console.log(res);
                                _this.setData({
                                    records:res.data.records
                                  })
                                  // app.globalData.records.status = 1;
                                console.log("recordsType:"+_this.data.records.type);
                                if(res.data.records.status==0){//没签到才能签
                                //更新签到
                                    wx.request({
                                      method:"POST",
                                      url:app.globalData.url+'v1/records/update',
                                      data:{  
                                        id:_this.data.records.id,
                                        userId:_this.data.role,
                                        courseId:_this.data.id,
                                        type:_this.data.records.type,
                                        status:_this.data.status,
                                        scores:_this.data.records.scores,
                                        comments:_this.data.records.comments
                                      },
                                      header:{  
                                        'content-type':'application/json'
                                      }, 
                                      
                                      success:function(res){
                                          console.log(res);                              
                                      },
                                  })
                           //按userid，查找出示二维码的人的user
                          wx.request({
                            url:app.globalData.url+'v1/user/'+_this.data.role, 
                            data:{  
                            },
                            header:{  
                              'content-type':'application/json'
                            }, 
                            // dataType:'JSON',  
                            // responseType:'text', 
                            success:function(res){
                                console.log(res);
                                _this.setData({
                                    user:res.data.user
                                  })
                                  console.log("userID:"+_this.data.user.id);
                                  console.log("userNAME:"+_this.data.user.name);
                                  console.log("userFACE:"+_this.data.user.face);
                                  console.log("userPOINTS:"+(_this.data.user.points+10));
                            
                         //更新points
                         var p=0;
                        if(_this.data.status==1){
                          p=10;//签到积分+10
                        }else if(_this.data.status==2){
                          p=-5;//迟到积分-5
                        }else{
                          p=-10;//不签-10
                        }          
                         wx.request({
                          method:"POST",
                          url:app.globalData.url+'v1/user/update',
                          data:{  
                            id:_this.data.user.id,
                            name:_this.data.user.name,
                            face:_this.data.user.face,
                            points:(_this.data.user.points+p)
                            
                          },
                          header:{  
                            'content-type':'application/json'
                          }, 
                          // dataType:'JSON',  
                          // responseType:'text', 
                          success:function(res){
                            console.log("increase points");
                              console.log(res);



                              //更新points显示
                              
                              //查userInfo
                              wx.request({
                                url: app.globalData.url + 'v1/user/'+app.globalData.userInfo.id,
                                method: 'get',
                                data: {
                                },
                                header: {
                                  'content-type': 'application/json' // 默认值
                                },
                                success (res) {
                                  console.log("onLoad:"+res);
                                 _this.setData({
                                    points: res.data.user.points
                                  })
                                // app.globalData.userInfo.points=res.data.user.points;

                                  wx.showToast({
                                    title: '扫码成功！',
                                    icon: 'success',
                                    duration: 1500
                                  })
                                  console.log("扫码成功！");
                                }
                              })                             
            
                      
                          },
                      })  
                                },
                        })

                                }else{
                                  wx.showToast({
                                    title: '你已签到！',
                                    icon: 'error',
                                    duration: 1500
                                  })
                                }

                            },
                        })

                        }else{
                          wx.showToast({
                            title: '课堂不能签到！',
                            icon: 'error',
                            duration: 1500
                          })
                          console.log("课堂不能签到！");
                        }
                                            
                    },
                })

                }else{
                  wx.showToast({
                    title: '你不是签到员！',
                    icon: 'error',
                    duration: 1500
                  })
                  console.log("你不是签到员！");
                }

        
            },
        })

        }
      }
    })
    // 只允许从相机扫码
    // wx.scanCode({
    //   onlyFromCamera: true,
    //   success: (res) => {
    //     console.log(res)
    //   }
    // })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  
  onReady: function () {
    console.log("onReady");
    var that=this;
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("onShow");
    var that=this;
    wx.request({
      url: app.globalData.url + 'v1/user/'+app.globalData.userInfo.id,
      method: 'get',
      data: {
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success (res) {
        // console.log("onLoad:"+res);
        that.setData({
          points: res.data.user.points
        })
      }
    })
  },
  getPoints:function(){

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("onHide");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  //刷新
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading(); 
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    wx.showLoading({
      title: '刷新中...',
    })
    this.getData();
  },
  //网络请求，获取数据
  getData(){
    var that=this;
    //更新积分
    wx.request({
      url: app.globalData.url + 'v1/user/'+app.globalData.userInfo.id,
      method: 'get',
      data: {
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      //网络请求执行完后将执行的动作
      complete(res){
        that.setData({
          points: res.data.user.points
        })
        console.log("points:"+that.data.points);
          //隐藏loading 提示框
          wx.hideLoading();
          //隐藏导航条加载动画
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
      }
})   
  },
  /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})